Mastering SVG by Rob Larsen

Mastering SVG by Rob Larsen

Author:Rob Larsen
Language: eng
Format: epub, mobi
Tags: COM060080 - COMPUTERS / Web / General, COM070000 - COMPUTERS / User Interfaces, COM051260 - COMPUTERS / Programming Languages / JavaScript
Publisher: Packt Publishing
Published: 2018-09-21T05:23:53+00:00


Again, if you're familiar with DOM manipulations, then you'll notice some differences here. This is where the NS variable comes into play. Since this isn't pure HTML and is, in fact, an entirely different document definition, we need to supply that namespace in order to create the element properly. So, instead of document.createElement, we have to use document.createElementNS and we pass in a second argument referencing the SVG namespace via the NS variable.

Once the element is created, we set the relevant attributes using elem.setAttribute. For the rect we set x, y, width, and height. For the circle we set r, cx, and cy. For the text element we set x, y and then set the text content using elem.textContent, which is a new wrinkle if you're used to updating text and/or HTML nodes with innerHTML. As mentioned previously, there is no innerHTML of an SVG element.

Once the elem is defined with the baseline attributes, we insert it into the document using the appendChild method. Finally, we remove the "active" class from the target SVG element, which will prevent further elements being added accidentally:

function add(event) {

const classes = canvas.classList;

const NS = canvas.getAttribute('xmlns');

const point = canvas.createSVGPoint()

point.x = event.offsetX;

point.y = event.offsetY;

const svgCoords =

point.matrixTransform(canvas.getScreenCTM().inverse());

let elem;

if (classes.contains("active")) {

if (classes.contains("square")) {

elem = doc.createElementNS(NS, "rect");

elem.setAttribute("x", svgCoords.x);

elem.setAttribute("y", svgCoords.y);

elem.setAttribute("width", 50);

elem.setAttribute("height", 50);



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.